<template>
  <div>
    <el-table
      ref="multipleTable"
      style="width: 100%"
      height="400px"
      v-bind="$attrs"
      @selection-change="handleSelectionChange"
    >
      <template slot="empty">
        <el-empty description="暂无数据"></el-empty>
      </template>
      <el-table-column type="selection"> </el-table-column>
      <el-table-column
        v-for="(item, index) in tableConfig"
        :key="index"
        :align="item.align"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
      >
        <template #default="{ row }">
          <slot :name="item.prop" :row="row">{{ row[item.prop] }}</slot>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      multipleSelection: []
    }
  },
  props: {
    tableConfig: {
      type: Array,
      default: () => []
    },
    name: {
      type: String,
      default: ''
    },
    default: {
      default: () => []
    }
  },
  watch: {
    multipleSelection: {
      handler (val) {
        this.$emit('selection-change', val)
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    if (this.default) {
      console.log('default', this.default)
      this.toggleSelection(this.default, true)
    }
  },
  methods: {
    handleSelectionChange (val) {
      this.multipleSelection = val.map((i) => String(i[this.name])).join(',')
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach((row) => {
          // const r = this.$attrs.data.find((i) => i.tableName === row.tableName)
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
